/*
 *  Copyright 2015 The WebRTC Project Authors. All rights reserved.
 *
 *  Use of this source code is governed by a BSD-style license
 *  that can be found in the LICENSE file in the root of the source
 *  tree. An additional intellectual property rights grant can be found
 *  in the file PATENTS.  All contributing project authors may
 *  be found in the AUTHORS file in the root of the source tree.
 */

package me.kevingleason.androidrtc;

import android.app.Activity;
import android.app.Fragment;
import android.app.ListFragment;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.SeekBar;
import android.widget.TextView;

import org.json.JSONException;
import org.json.JSONObject;
import org.webrtc.VideoRendererGui.ScalingType;

import java.util.LinkedList;
import java.util.List;

import me.kevingleason.androidrtc.adapters.ChatAdapter;
import me.kevingleason.androidrtc.adt.ChatMessage;
import me.kevingleason.androidrtc.util.Constants;

/**
 * Fragment for call control.
 */
public class CallFragment extends Fragment {
    private View controlView;
    private TextView contactView;
    private ImageButton disconnectButton;
    private ImageButton cameraSwitchButton;
    private ImageButton videoScalingButton;
    private ImageButton toggleMuteButton;
    private ScalingType scalingType;
    private boolean videoCallEnabled = true;
    private EditText mChatEditText;
    private ImageButton send_message;
    protected ListView mChatList;
    private ChatAdapter mChatAdapter;

    private VideoChatActivity mActivity;

    private String contactName;

    /**
     * Call control interface for container activity.
     */
    public interface OnCallEvents {
        void onCallHangUp();

        void onCameraSwitch();

        void onVideoScalingSwitch(ScalingType scalingType);

        boolean onToggleMic();
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        mActivity = (VideoChatActivity) activity;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Bundle args = getArguments();
        if (args != null) {
            contactName = args.getString(Constants.USER_NAME);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        controlView =
                inflater.inflate(R.layout.fragment_call, container, false);

        this.mChatList = (ListView) controlView.findViewById(R.id.call_list);
        this.mChatEditText = (EditText) controlView.findViewById(R.id.chat_input);
        this.send_message = (ImageButton) controlView.findViewById(R.id.send_message);
        // Create UI controls.
        contactView =
                (TextView) controlView.findViewById(R.id.contact_name_call);
        disconnectButton =
                (ImageButton) controlView.findViewById(R.id.button_call_disconnect);
        cameraSwitchButton =
                (ImageButton) controlView.findViewById(R.id.button_call_switch_camera);
        videoScalingButton =
                (ImageButton) controlView.findViewById(R.id.button_call_scaling_mode);
        toggleMuteButton =
                (ImageButton) controlView.findViewById(R.id.button_call_toggle_mic);

        // Add buttons click events.
        disconnectButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mActivity.onCallHangUp();
            }
        });

        cameraSwitchButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mActivity.onCameraSwitch();
            }
        });

        videoScalingButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (scalingType == ScalingType.SCALE_ASPECT_FILL) {
                    videoScalingButton.setBackgroundResource(
                            R.drawable.ic_action_full_screen);
                    scalingType = ScalingType.SCALE_ASPECT_FIT;
                } else {
                    videoScalingButton.setBackgroundResource(
                            R.drawable.ic_action_return_from_full_screen);
                    scalingType = ScalingType.SCALE_ASPECT_FILL;
                }
                mActivity.onVideoScalingSwitch(scalingType);
            }
        });
        scalingType = ScalingType.SCALE_ASPECT_FILL;

        toggleMuteButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                boolean enabled = mActivity.onToggleMic();
                toggleMuteButton.setAlpha(enabled ? 1.0f : 0.3f);
            }
        });

        send_message.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                sendMessage();
            }
        });

        // Set up the List View for chatting
        List<ChatMessage> ll = new LinkedList<ChatMessage>();
        mChatAdapter = new ChatAdapter(mActivity.getApplicationContext(), ll);
        mChatList.setAdapter(mChatAdapter);

        contactView.setText(contactName + " Connecting...");
        return controlView;
    }

    public void sendMessage() {
        String message = mChatEditText.getText().toString();
        if (message.equals("")) return; // Return if empty
        ChatMessage chatMsg = new ChatMessage(this.contactName, message, System.currentTimeMillis());
        mChatAdapter.addMessage(chatMsg);
        JSONObject messageJSON = new JSONObject();
        try {
            messageJSON.put(Constants.JSON_MSG_UUID, chatMsg.getSender());
            messageJSON.put(Constants.JSON_MSG, chatMsg.getMessage());
            messageJSON.put(Constants.JSON_TIME, chatMsg.getTimeStamp());
            mActivity.pnRTCClient.transmitAll(messageJSON);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        // Hide keyboard when you send a message.
        View focusView = mChatEditText.findFocus();
        if (focusView != null) {
            InputMethodManager inputManager = (InputMethodManager) mActivity.getSystemService(Context.INPUT_METHOD_SERVICE);
            inputManager.hideSoftInputFromWindow(mChatEditText.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
        }
        mChatEditText.setText("");
    }

    @Override
    public void onStart() {
        super.onStart();

        if (!videoCallEnabled) {
            cameraSwitchButton.setVisibility(View.INVISIBLE);
        }
    }

    public void setContactsStatus(String content) {
        contactView.setText(content);
    }

    public void setContactsVisibility(int visibility) {
        contactView.setVisibility(visibility);
    }

    public void addChatMsg(final ChatMessage chatMsg){
        mActivity.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                mChatAdapter.addMessage(chatMsg);
            }
        });
    }
}
